import logging

from django.http import HttpRequest
from functools import wraps

from gis.admin import const
from gis.admin.exceptions import ERROR_USER_INVALID_TOKEN, ERROR_PERMISSION_NOT_AUTHORIZED, ERROR_AUTH_TOKEN
from gis.admin.services import admin_service
from gis.common.exceptions import BizException

_LOGGER = logging.getLogger(__name__)


def require_login(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        request = args[0]
        assert isinstance(request, HttpRequest)
        if not request.session.get(const.SESSION_USER_KEY):
            raise BizException(ERROR_USER_INVALID_TOKEN)
        else:
            request.user_id = request.session[const.SESSION_USER_KEY]
            request.user = admin_service.get_user_by_id(request.user_id)
            request.pro_id = request.user.get('pro_id')
            request.session.modified = True
        return func(*args, **kwargs)

    return wrapper


def check_permission(permission_code):
    def decorator(func):
        def wrapper(*args, **kwargs):
            request = args[0]
            assert isinstance(request, HttpRequest)
            all_permission_codes = admin_service.get_user_all_permission_codes(request.user_id)
            perms = set(permission_code) if isinstance(permission_code, list) else {permission_code}
            # perms 是否在 all_permission_codes 中
            if not perms.intersection(all_permission_codes):
                raise BizException(ERROR_PERMISSION_NOT_AUTHORIZED)
            return func(*args, **kwargs)

        return wrapper

    return decorator


def require_token(func):
    @wraps(func)
    def _wrapper(request, *args, **kwargs):
        user_id, token, pro_id = request.META.get('HTTP_X_AUTH_USER'), request.META.get(
            'HTTP_X_AUTH_TOKEN'), request.META.get('HTTP_X_AUTH_PROID')
        if not admin_service.check_auth_token(user_id, token, pro_id):
            raise BizException(ERROR_AUTH_TOKEN)
        return func(request, *args, **kwargs)
    return _wrapper
